<?php
namespace app\qsapi\service;

use app\qsapi\model\BoxGameCate;
use app\qsapi\model\BoxGame;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class GameService extends BaseService
{
    /**
     * 游戏分类列表
     * @return array
     */
    public function cateList(): array
    {
        $gameCateModel = new  BoxGameCate();
        $where[] = ['status', '=', 1];
        $where[] = ['mark', '=', 1];
        $list = $gameCateModel->where($where)->field('id,name,sort');
        $platform = strtolower($this->platform) ?? '';
        if (isset($this->adDevice[$platform])) {
            $list = $list->where(function ($query) use ($platform) {
                $query->where(Db::raw("FIND_IN_SET('1',device)"));
                if (isset($this->adDevice[$platform])) {
                    $device = $this->adDevice[$platform];
                    $query->whereOr(Db::raw("FIND_IN_SET('{$device}',device)"));
                }
            });
        }
        $list = $list->order('sort desc')->select();
        return api_message($list ? $list->toArray() : []);

    }

    /**
     * 游戏列表
     * @return array
     */
    public function getList(): array
    {
        $param = request()->param();
        $limit = $param['limit'] ?? 10;
        $gameModel = new BoxGame();
        $gameModel = $gameModel->alias('g');
        $list = $gameModel->where('g.mark', 1)->whereIn('g.status', [1, 3]);
        $ip = get_client_ip();
        $list = $list->where("g.white = '' OR g.white = '{$ip}'");
        if (!empty($param['name'])) { //名称
            $list = $list->where('g.game_name', 'like', '%' . trim($param['name']) . '%');
        }
        $whereCate[]   = ['status', '=', 1];
        $whereCate[]   = ['mark', '=', 1];
        $gameCateModel = new  BoxGameCate();
        $cate_list     = $gameCateModel->where($whereCate)->field('id,name,sort')->order('sort desc')->select();
        $cate_list     = array_column($cate_list ? $cate_list->toArray() : [], null, 'id');


        $list = $list->order('g.id', 'desc');
        $list = $list->field('g.id,g.game_name,g.icon,g.content,g.cate_id,g.status,g.android_download_url,g.ios_download_url,g.android_param,g.ios_param,g.open_type,g.android_package_name,g.android_bag')->paginate($limit);
        if ($list->total() <= 0) return api_message(['list' => [], 'total' => 0]);
        $list = $list->toArray();
        foreach ($list['data'] as $k => &$item){
            $labels = [];
            if ($item['cate_id']) {
                $cate_ids = explode(",", $item['cate_id']);
                foreach ($cate_ids as $i => $v) {
                    if (isset($cate_list[$v])) {
                        $labels[$i] = $cate_list[$v]['name'];
                    }
                }
            }
            $item['android_bag'] = explode(',',$item['android_bag']);
            $item['labels'] = array_values($labels);
            $item['android_param'] = $item['android_param'] ? json_decode($item['android_param'], true) : [];
            $item['ios_param'] = $item['ios_param'] ? json_decode($item['ios_param'], true) : [];
            $android_res = [];
            $ios_res = [];
            foreach ($item['android_param'] as $value){
                $key = $value['item'] ?? '';
                $val = $value['value'] ?? '';
                $android_res[$key] = $val;
            }
            foreach ($item['ios_param'] as $value){
                $key = $value['item'] ?? '';
                $val = $value['value'] ?? '';
                $ios_res[$key] = $val;
            }
            $item['android_param'] = $android_res;
            $item['ios_param'] = $ios_res;
        }

        $data['list'] = $list['data'];
        $data['total'] = $list['total'];
        return api_message($data);
    }

    /**
     * 游戏详情
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getInfo($id): array
    {
        try {
            $member_id = request()->getMemberId();
        } catch (\Throwable $e) {
            $member_id = 0;
        }
        $gameModel = new BoxGame();
        $gameModel = $gameModel->alias('g');;
        $info = $gameModel->field('g.id,g.app_id,g.package_id,g.game_name,g.icon,g.cate_id,g.status,g.content,g.game_info,g.version,g.game_banner')
            ->where('g.id', $id)->where('g.mark', 1)->find();
        if (!$info) {
            return api_message([], '游戏不存在', 0);
        }
        $info = $info->toArray();
        $game_banner = $info['game_banner'] ? json_decode($info['game_banner'], true) : [];
        $info['game_banner'] = [];
        if ($game_banner) {
            foreach ($game_banner as $k => $item) {
                if (isset($item['data'])) {
                    if (in_array($item['type'], ['mp4'])) {
                        $game_banner[$k]['type'] = 2;
                    } else {
                        $game_banner[$k]['type'] = 1;
                    }
                    if (!isset($item['img'])) {
                        $game_banner[$k]['img'] = '';
                    }
                    $info['game_banner'] = $game_banner;
                } else {
                    array_push($info['game_banner'], ['data' => $item, 'img' => '', 'type' => 1]);
                }
            }
        }


        if ($info['cate_id']) {
            $gameCateModel = new  BoxGameCate();
            $whereCate[] = ['status', '=', 1];
            $whereCate[] = ['mark', '=', 1];
            $whereCate[] = ['id', 'in', $info['cate_id']];
            $cate_list = $gameCateModel->where($whereCate)->field('id,name,sort')->order('sort desc')->select()->toArray();
            $info['cate_labels'] = array_column($cate_list ?? [], 'name');
        }

        $data['game'] = $info;
        return api_message($data);
    }
}
